package hong.jun;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import dev.morphia.Datastore;
import dev.morphia.Morphia;
import hong.jun.cfg.MongoSettingsProperties;

/**
 * @Description:
 * @Author: yanghongjun
 * @Date: 2023/11/17
 **/
public class MongoMgr {

    /**
     * 用枚举来实现单例
     */
    private enum Singleton {
        INSTANCE;
        final MongoMgr processor;

        Singleton() {
            this.processor = new MongoMgr();
        }

        MongoMgr getProcessor() {
            return processor;
        }
    }

    /**
     * 获取实例对象
     */
    public static MongoMgr getInstance() {
        return MongoMgr.Singleton.INSTANCE.getProcessor();
    }
    private final MongoClient mongoClient;
    private final Datastore datastore;


    public MongoMgr() {
        //连接池配置
        MongoSettingsProperties properties = new MongoSettingsProperties();
        properties.setUri("mongodb://127.0.0.1:27017/My-test?authSource=admin");
        properties.setConntectTimeout(10000);//链接超时时间
        properties.setSocketTimeout(10000);//read数据超时时间
        properties.setMaxWaitTimeout(10000);//长链接的最大等待时间
        properties.setConnectionsPerhost(20);//每个地址最大请求数
        properties.setConnectionsIdleTime(12000);//链接最大闲置时间
        properties.setAllowedToblockForConnectionMultipier(10);//线程队列数
        //设置连接属性
        MongoClientOptions.Builder options = MongoClientOptions.builder();
        options.connectTimeout(properties.getConntectTimeout());
        options.socketTimeout(properties.getSocketTimeout());
        options.maxWaitTime(properties.getMaxWaitTimeout());
        options.connectionsPerHost(properties.getConnectionsPerhost());
        options.maxConnectionIdleTime(properties.getConnectionsIdleTime());
        options.serverSelectionTimeout(properties.getMaxWaitTimeout());
        options.threadsAllowedToBlockForConnectionMultiplier(properties.getAllowedToblockForConnectionMultipier());
        MongoClientURI uri = new MongoClientURI(properties.getUri(), options);
        // 创建客户端和Factory
        mongoClient = new MongoClient(uri);
        //创建Datastore
        Morphia res = new Morphia();
        // 确定Mongo实体类的存放包名
        res.mapPackage("hong.jun.data");
        datastore = res.createDatastore(mongoClient, uri.getDatabase());
        datastore.ensureIndexes();
    }

    public MongoClient getMongoClient() {
        return mongoClient;
    }

    public Datastore getDatastore() {
        return datastore;
    }


}
